package org.jeecg.modules.mp.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.JwidModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.RestUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.config.mybatis.TenantContext;
import org.jeecg.modules.arc.entity.ArcAccount;
import org.jeecg.modules.arc.service.IArcAccountService;
import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.modules.mp.entity.JwWebJwid;
import org.jeecg.modules.mp.service.IJwWebJwidService;
import org.jeecg.modules.mp.vo.SuggestVo;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysTenantService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 公众号
 * @Author: jeecg-boot
 * @Date:   2022-04-12
 * @Version: V1.0
 */
@Api(tags="公众号")
@RestController
@RequestMapping("/mp/jwWebJwid")
@Slf4j
public class JwWebJwidController extends JeecgController<JwWebJwid, IJwWebJwidService> {
	@Autowired
	private IJwWebJwidService jwWebJwidService;
	@Autowired
	private IArcAccountService accountService;

	@Autowired
	private ISysBaseAPI baseAPI;
	@Autowired
	private ISysUserService sysUserService;
	@Resource
	private ISysTenantService tenantService;
	@Resource
	private BaseCommonService baseCommonService;
	@Autowired
	private RedisUtil redisUtil;


	/**
	 * 跳转到活动首页
	 *
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/toIndex", method = {RequestMethod.GET, RequestMethod.POST})
	public void toIndex(@ModelAttribute JwWebJwid weixinDto, HttpServletRequest request, HttpServletResponse response, ModelMap model) throws Exception {
//		 LOG.info(request, "toIndex parameter WeixinDto={}.", new Object[]{weixinDto});
		log.info("toIndex parameter WeixinDto={}.", new Object[]{weixinDto});

		//====================================================================================================
		//装载微信所需参数
		String jwid = weixinDto.getJwid();
		String appid = weixinDto.getWeixinAppid();
		log.info("---------appid---------------" + appid);

		//VelocityContext velocityContext = new VelocityContext();
		String viewName = null;
		try {
			String regId="";
			//美团
			viewName = "gzbargain/co/vm/index.vm";


			//velocityContext.put("recordListCount", bargainRecordList == null ? 0 : bargainRecordList.size());
			//velocityContext.put("recordList", bargainRecordList);
			//velocityContext.put("weixinDto", weixinDto);

			//velocityContext.put("hdUrl", gzWxActBargain.getHdurl()); //获取分享URL
			//velocityContext.put("appId", appid);
			//velocityContext.put("signature", WeiXinHttpUtil.getRedisSignature(request, jwid));// 必填，签名，见附录1

			//update-begin-----author:scott---------date:21050809------for:微信分享参数------------------
			//ViewVelocity.view(request, response, viewName, velocityContext);

			response.setHeader("Access-Control-Allow-Origin", "*");
			/*星号表示所有的域都可以接受，*/
			response.setHeader("Access-Control-Allow-Methods", "GET,POST");


			response.sendRedirect("http://localhost:8081/#/pages/index/index?jwid=" + jwid);

		} catch (Exception e) {
			log.error("toIndex error:{}", e);
			viewName = "gzbargain/vm/default/error.vm";
			//velocityContext.put("errCode", GzbargainExceptionEnum.SYS_ERROR.getErrCode());
			//velocityContext.put("errMsg", GzbargainExceptionEnum.SYS_ERROR.getErrChineseMsg());
		}
	}

	 /**
	  * 获取openid 并登录
	  * @param
	  * @param
	  * @return
	  */
	 @CrossOrigin
	 @GetMapping("/openLogin")
	 @ResponseBody
	 public Result<?> openLogin(JwWebJwid jwWebJwid,HttpServletRequest request, HttpServletResponse response){
		 JSONObject param=new JSONObject();
		 param.put("jwid",jwWebJwid.getJwid());
		 JwidModel jwidModel = baseAPI.getJwId(param);
		 if(null!= jwidModel){
		 	return Result.error("公众号jw不存在");
		 }
		 String appid= jwidModel.getWeixinAppid();
		 String secret = jwidModel.getWeixinAppsecret();
		 response.setHeader("Access-Control-Allow-Origin", "*");
		 /*星号表示所有的域都可以接受，*/
		 response.setHeader("Access-Control-Allow-Methods", "GET,POST");
		 String wxLoginUrl = "https://api.weixin.qq.com/sns/oauth2/access_token";
		 String paramStr = "appid="+appid+"&secret="+secret+"&code="+jwWebJwid.getCode()+"&grant_type=authorization_code";

		 JSONObject params=new JSONObject();
		 params.put("grant_type","authorization_code");
		 params.put("appid",appid);
		 params.put("secret",secret);
		 params.put("code",jwWebJwid.getCode());
		 JSONObject jsonObject = RestUtil.get(wxLoginUrl, params);
		 if(jsonObject.containsKey("errcode") && !"0".equals(jsonObject.getString("errcode"))){
			 return Result.error("获取微信信息异常");
		 }
		 System.out.println(jsonObject.toJSONString());
		 //String jsonString = HttpUtil.sendGet(wxLoginUrl, param);
		 //JSONObject json = JSONObject.parseObject(jsonString);
		 String openid = jsonObject.getString("openid");
		 System.out.println("###############"+openid);


		 //租户统一微信公众号专用收费账号登录 wx
		 String pinyin = jwidModel.getTenantPinyin();
		 String username=pinyin+"Wxsf";

		 //1. 校验用户是否有效
		 SysUser sysUser = sysUserService.getUserByName(username);
		 Result result = sysUserService.checkUserIsEffective(sysUser);
		 if(!result.isSuccess()) {
			log.info(result.getMessage());
			 return result;
		 }

			 //2. 校验用户名或密码是否正确
			 //String userpassword = PasswordUtil.encrypt(username, password, sysUser.getSalt());
			 //String syspassword = sysUser.getPassword();
			 //if (!syspassword.equals(userpassword)) {
				// result.error500("用户名或密码错误");
				// return result;
			 //}

			 //String orgCode = sysUser.getOrgCode();
			 //if(oConvertUtils.isEmpty(orgCode)) {
				// //如果当前用户无选择部门 查看部门关联信息
				// List<SysDepart> departs = sysDepartService.queryUserDeparts(sysUser.getId());
				// if (departs == null || departs.size() == 0) {
				//	 result.error500("用户暂未归属部门,不可登录!");
				//	 return result;
				// }
				// orgCode = departs.get(0).getOrgCode();
				// sysUser.setOrgCode(orgCode);
				// this.sysUserService.updateUserDepart(username, orgCode);
			 //}
		 JSONObject obj = new JSONObject();
		 //用户登录信息
		 obj.put("userInfo", sysUser);

		 String tenantIds = sysUser.getRelTenantIds();
		 if (oConvertUtils.isNotEmpty(tenantIds)) {
			 List<String> tenantIdList = Arrays.asList(tenantIds.split(","));
			 TenantContext.setTenant(tenantIdList.get(0));
		 }

		 //获取用户openid\wx_token
		 obj.put("openid", openid);
		 obj.put("jwid", jwidModel.getJwid());

		 //已绑定的缴费账户
		 List<ArcAccount> accountList = accountService.list(new LambdaQueryWrapper<ArcAccount>()
				 .eq(ArcAccount::getWeixinId, openid)
				 .eq(ArcAccount::getStatus, "1")
				 .eq(ArcAccount::getDelFlag, 0));

		 if(null != accountList && accountList.size()>0) {
			 ArcAccount arcAccount = accountList.get(0);
			 obj.put("accCode", arcAccount.getCode());
		 }

		 // 生成token
		 String syspassword="12341234";
		 String token = JwtUtil.sign(username, syspassword);
		 // 设置超时时间
		 redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
		 redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME*2 / 1000);

		 //token 信息
		 obj.put("token", token);
		 result.setResult(obj);
		 result.setSuccess(true);
		 result.setCode(200);
		 baseCommonService.addLog("用户名: " + username + ",登录成功[移动端]！", CommonConstant.LOG_TYPE_1, null);
		 return result;

	 }
	 /**
	  * 获取openid
	  * @param
	  * @param
	  * @return
	  */
	 @CrossOrigin
	 @GetMapping("/openidBind")
	 @ResponseBody
	 public Result<?> openidBind(JwWebJwid jwWebJwid,HttpServletRequest request, HttpServletResponse response){

		 String openid = request.getHeader("X-Openid");
		 if(oConvertUtils.isEmpty(openid)){
			 openid=jwWebJwid.getOpenid();
		 }

		 if(oConvertUtils.isEmpty(openid)){
			 return Result.error("会话异常请重新进入");
		 }
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 String tenantIds = sysUser.getRelTenantIds();
		 if (oConvertUtils.isNotEmpty(tenantIds)) {
			 List<String> tenantIdList = Arrays.asList(tenantIds.split(","));
			 TenantContext.setTenant(tenantIdList.get(0));
		 }

		 List<ArcAccount> arcAccounts = accountService.getAccountByCodeMobile(jwWebJwid.getAccount(), jwWebJwid.getPhone());

		 if(null != arcAccounts && arcAccounts.size()>0){
			 ArcAccount arcAccount = arcAccounts.get(0);
			 arcAccount.setWeixinId(openid);
			 accountService.updateById(arcAccount);
		 }else{
			 return Result.error("账户信息不存在");
		 }


		 return Result.OK("绑定成功");
	 }
	 /**
	  * 获取openid
	  * @param
	  * @param
	  * @return
	  */
	 @CrossOrigin
	 @GetMapping("/getJwAppid")
	 public Result<?> getJwAppid(JSONArray params){
		 System.out.println("getJwAppid:"+params.toJSONString());
		 if(null == null || params.size() == 0){
			 return Result.error("no");
		 }
		 JSONObject param = (JSONObject) params.get(0);
		 JwidModel jwidModel = baseAPI.getJwId(param);
		 if(null == jwidModel){
			 return Result.error("客户没有配置公众号");
		 }
		 return Result.OK(jwidModel.getWeixinAppid());
	 }
	 /**
	  * 提交意见
	  */
	 @CrossOrigin
	 @PostMapping("/submitSug")
	 public Result<?> submitSug(SuggestVo suggestVo){
	 	//意见表 /online/cgformList/402881a9802c683001802c6af7a20001

		 String sugCode="402881a9802c683001802c6af7a20001";

		 if(oConvertUtils.isEmpty(TenantContext.getTenant())){
			 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			 String tenantIds = sysUser.getRelTenantIds();
			 if (oConvertUtils.isNotEmpty(tenantIds)) {
				 List<String> tenantIdList = Arrays.asList(tenantIds.split(","));
				 TenantContext.setTenant(tenantIdList.get(0));
			 }
		 }

		 JSONObject jsonSug=new JSONObject();
		 jsonSug.put("title",suggestVo.getTitle());
		 jsonSug.put("content",suggestVo.getContent());
		 jsonSug.put("acc_code",suggestVo.getAccCode());
		 jsonSug.put("openid",suggestVo.getOpenid());
		 jsonSug.put("status","1");
		 baseAPI.createOnlineData(sugCode,jsonSug);
		 return Result.OK("提交成功");
	 }

	/**
	 * 分页列表查询
	 *
	 * @param jwWebJwid
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "公众号-分页列表查询")
	@ApiOperation(value="公众号-分页列表查询", notes="公众号-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(JwWebJwid jwWebJwid,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<JwWebJwid> queryWrapper = QueryGenerator.initQueryWrapper(jwWebJwid, req.getParameterMap());
		Page<JwWebJwid> page = new Page<JwWebJwid>(pageNo, pageSize);
		IPage<JwWebJwid> pageList = jwWebJwidService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   生成短地址
	 *
	 * @param jwWebJwid
	 * @return
	 */
	@AutoLog(value = "公众号-生成短地址")
	@ApiOperation(value="公众号-生成短地址", notes="公众号-生成短地址")
	@PostMapping(value = "/createShort")
	public Result<?> createShort(@RequestBody JwWebJwid jwWebJwid) {
		JSONObject param=new JSONObject();
		param.put("jwid",jwWebJwid.getJwid());
		JwidModel jwidModel = baseAPI.getJwId(param);
		if(null== jwidModel){
			return Result.error("公众号jw不存在");
		}
		String urlpath=jwidModel.getHdUrl();
		String accessToken=jwidModel.getAccessToken();

		if(oConvertUtils.isNotEmpty(urlpath)){
			if(urlpath.contains("/#/pages/index/index")){
				urlpath=urlpath.substring(0,urlpath.indexOf("/#/pages/index/index"));
			}
			urlpath=urlpath+"/#/pages/index/index?jwid="+jwidModel.getJwid()+"&appid="+jwidModel.getWeixinAppid();
		}else{
			return Result.error("菜单域名不能为空！");
		}

		Map<String, Object> paramMap = new HashMap();
		paramMap.put("action", "long2short");
		paramMap.put("long_url", urlpath);
		JSONObject obj = new JSONObject(paramMap);
		log.info("getShortUrl request jsonStr={}.", new Object[]{obj.toString()});
		JSONObject jsonStr = RestUtil.post("https://api.weixin.qq.com/cgi-bin/shorturl?access_token=" + accessToken, obj);
		log.info("getShortUrl response jsonStr={}.", jsonStr.toJSONString());
		if (jsonStr != null) {

			if (jsonStr.containsKey("errcode") && "0".equals(jsonStr.getString("errcode")) && jsonStr.containsKey("short_url")) {
				String shortUrl = jsonStr.getString("short_url").replaceAll("\\/", "/");
				log.info("getShortUrl response short_url={}.", new Object[]{shortUrl});
				JwWebJwid webJwid = jwWebJwidService.getById(jwidModel.getId());
				webJwid.setHdUrl(shortUrl);
				jwWebJwidService.updateById(webJwid);
				return Result.OK("生成短地址成功！");
			}else{
				return Result.error(jsonStr.getString("errmsg"));
			}
		}
		return Result.OK("生成短地址成功！");
	}
	/**
	 *   添加
	 *
	 * @param jwWebJwid
	 * @return
	 */
	@AutoLog(value = "公众号-添加")
	@ApiOperation(value="公众号-添加", notes="公众号-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody JwWebJwid jwWebJwid) {
		jwWebJwidService.save(jwWebJwid);
		return Result.OK("添加成功！");
	}
	/**
	 *   授权
	 *
	 * @param jwWebJwid
	 * @return
	 */
	@AutoLog(value = "公众号-授权")
	@ApiOperation(value="公众号-授权", notes="公众号-授权")
	@PostMapping(value = "/authToken")
	public Result<?> authToken(@RequestBody JwWebJwid jwWebJwid) {
		return jwWebJwidService.authToken(jwWebJwid);
	}

	/**
	 *  编辑
	 *
	 * @param jwWebJwid
	 * @return
	 */
	@AutoLog(value = "公众号-编辑")
	@ApiOperation(value="公众号-编辑", notes="公众号-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody JwWebJwid jwWebJwid) {
		jwWebJwidService.updateById(jwWebJwid);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "公众号-通过id删除")
	@ApiOperation(value="公众号-通过id删除", notes="公众号-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		jwWebJwidService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "公众号-批量删除")
	@ApiOperation(value="公众号-批量删除", notes="公众号-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.jwWebJwidService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "公众号-通过id查询")
	@ApiOperation(value="公众号-通过id查询", notes="公众号-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		JwWebJwid jwWebJwid = jwWebJwidService.getById(id);
		if(jwWebJwid==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(jwWebJwid);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param jwWebJwid
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, JwWebJwid jwWebJwid) {
        return super.exportXls(request, jwWebJwid, JwWebJwid.class, "公众号");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, JwWebJwid.class);
    }

}
